package _interview100;

/**
 * 1143. 最长公共子序列
 */
public class No1143 {
    private String text1, text2;
    private int[][] cache;

    public int longestCommonSubsequence1(String text1, String text2) {
        this.text1 = text1;
        this.text2 = text2;
        int m = text1.length();
        int n = text2.length();
        cache = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                cache[i][j] = -1;
            }
        }
        return dfs(m - 1, n - 1);
    }

    private int dfs(int i, int j) {
        if (i < 0 || j < 0) return 0;
        else if (cache[i][j] != -1) return cache[i][j];
        else if (text1.charAt(i) == text2.charAt(j)) return cache[i][j] = dfs(i - 1, j - 1) + 1;
        else return cache[i][j] = Math.max(dfs(i - 1, j), dfs(i, j - 1));
    }

    public int longestCommonSubsequence2(String text1, String text2) {
        int m = text1.length();
        int n = text2.length();
        int[][] f = new int[m + 1][n + 1];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (text1.charAt(i) == text2.charAt(j)) f[i + 1][j + 1] = f[i][j] + 1;
                else f[i + 1][j + 1] = Math.max(f[i][j + 1], f[i + 1][j]);
            }
        }
        return f[m][n];
    }

    public int longestCommonSubsequence4(String text1, String text2) {
        int m = text1.length();
        int n = text2.length();
        int[] f = new int[n + 1];
        for (int i = 0; i < m; i++) {
            int pre = f[0];
            for (int j = 0; j < n; j++) {
                int temp = f[j + 1];
                if (text1.charAt(i) == text2.charAt(j)) f[j + 1] = pre + 1;
                else f[j + 1] = Math.max(f[j + 1], f[j]);
                pre = temp;
            }
        }
        return f[n];
    }
}
